/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { fork } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';

import { logError, logFormatedErrorAndExit, logInfo } from './log.js';
import { calcChildExecArgv } from '../common/util/cacl-exec-argv-util.js';

/**
 * 启动hvigor构建
 */
export function executeBuild(hvigorProjectDependenciesHome: string) {
  const hvigorBootJsFilePath = path.resolve(hvigorProjectDependenciesHome, 'node_modules', '@ohos', 'hvigor', 'bin', 'hvigor.js');

  try {
    // 由于hvigorBootJsFilePath是一个软链接,必须使用下列接口获取真实路径,使用require直接执行上述软链接路径会出现路径错误
    const realBootJsFilePath = fs.realpathSync(hvigorBootJsFilePath);
    const args = process.argv.slice(2);
    const childProcess = fork(realBootJsFilePath, args, {
      env: process.env,
      execArgv: calcChildExecArgv(),
    });
    childProcess.stdout?.on('data', (data) => {
      logInfo(`${data.toString().trim()}`);
    });

    childProcess.stderr?.on('data', (data) => {
      logError(`${data.toString().trim()}`);
    });

    childProcess.on('exit', (code, signal) => {
      process.exit(code ?? -1);
    });
  } catch (e) {
    logFormatedErrorAndExit('00308003', `ENOENT: no such file ${hvigorBootJsFilePath}`, [`delete ${hvigorProjectDependenciesHome} and retry.`]);
  }
}
